package demogo

import (
	"fmt"
	"strings"
)

type LinkedNode struct {
	next *LinkedNode
	v    int
}

type LinkedList struct {
	head   *LinkedNode
	length int
}

func (l *LinkedList) Reverse() {
	if l.head == nil {
		return
	}
	// 1->2->3->4
	// <-1<-2<-3<-4
	var pre *LinkedNode = nil
	cur := l.head.next
	for cur != nil {
		tmp := cur.next
		cur.next = pre
		pre = cur
		cur = tmp
	}
	l.head.next = pre

	{
		if l.head == nil {
			return
		}
		var pre *LinkedNode = nil
		cur := l.head.next
		for cur != nil {
			tmp := cur.next
			cur.next = pre
			pre = cur
			cur = tmp
		}
		l.head.next = pre
	}
}

func (l *LinkedList) HasCycle() bool {
	if l.head == nil || l.head.next == nil {
		return false
	}
	slow := l.head
	fast := l.head
	for fast != nil && fast.next != nil {
		slow = slow.next
		fast = fast.next.next
		if fast == slow {
			return true
		}
	}

	return false
}

func (l *LinkedList) Print() {
	cur := l.head.next
	format := strings.Builder{}
	for cur != nil {
		format.WriteString(fmt.Sprintf("%+v", cur.v))
		cur = cur.next
		if cur != nil {
			format.WriteString("->")
		}
	}
	fmt.Println(format.String())
}
